package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.DON_VI_TCM;
import model.MonHocM;
import net.sf.json.JSONObject;
import dao.DON_VI_TCD;
import dao.MonHocD;

/**
 * Servlet implementation class ExcelServlet
 */
@WebServlet("/ExcelServlet")
public class ExcelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MonHocD dao;
	private DON_VI_TCD dv;
	private ArrayList<MonHocM> mhs = null;

	/**
	 * @throws Exception
	 * @see HttpServlet#HttpServlet()
	 */
	public ExcelServlet() throws Exception {
		super();
		this.dao = new MonHocD();
		this.dv = new DON_VI_TCD();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setHeader("Cache-control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "-1");

		String flag = request.getParameter("flag");
		System.out.println(flag);
		String name = request.getParameter("name");
		try {
			if (flag == null && name == null) {
				RequestDispatcher view = request.getRequestDispatcher("ImportMonHoc.jsp");
				view.forward(request, response);
			} else if (name != null) {
				String path = "/home/vietdao/" + name;
				showImport(path, request, response);
			} else if ("test".equals(flag.trim()) && flag != null) {
				testData(mhs, request, response);
			} else if ("import".equals(flag.trim()) && flag != null) {
				importData(request, response);
			} else {
				RequestDispatcher view = request.getRequestDispatcher("ImportMonHoc.jsp");
				view.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @function show Import
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void showImport(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String pageCount = request.getParameter("page");
		String rowsCount = request.getParameter("rows");

		int page = (pageCount == null || "".equals(pageCount)) ? 1 : Integer.valueOf(pageCount);
		int rows = (rowsCount == null || "".equals(rowsCount)) ? 10 : Integer.valueOf(rowsCount);

		int offSet = (page - 1) * rows;
		int allCount = dao.readExcel9703(fileName).size();
		mhs = dao.readExcel9703(fileName);
		returnMap.put("total", allCount);
		returnMap.put("rows", mhs);
		String returnString = JSONObject.fromObject(returnMap).toString();
		PrintWriter out = response.getWriter();
		out.println(returnString);
		out.flush();
		out.close();
	}

	/**
	 * @function test database with excel file
	 * @param excel
	 * @return
	 * @throws Exception
	 */
	public int checkExists(ArrayList<MonHocM> excel) throws Exception{
		int find = 0;
		int i = 0;
		int check = 0;
		ArrayList<MonHocM> data = dao.getAllLoad1();
		while((i < data.size()) && (find == 0)){
			int j = 0;
			while(j < excel.size()){
				
				if(data.get(i).getMa().trim().equals(excel.get(j).getMa().trim())){
					find = 1;
					check = j;
					break;
				}else
					j++;
			}
			i++;
		}
		return check;
	}
	
	/**
	 * @function test database with excel file
	 * @param excel
	 * @return
	 * @throws Exception
	 */
	public void testData(ArrayList<MonHocM> excel, HttpServletRequest request, HttpServletResponse response) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		int check = checkExists(excel);
		if(check > 0){
			map.put("success", "false");
			map.put("msg", "Mã môn học " + excel.get(check).getMa() + " đã tồn tại trong cở sở dữ liệu");
		}else{
			map.put("success", "true");
			map.put("msg", "Kiểm tra thành công");
		}
		String returnFlag = JSONObject.fromObject(map).toString();
		PrintWriter out = response.getWriter();
		out.println(returnFlag);
		out.flush();
		out.close();
	}
	
	
	/**
	 * @function import data from excel file to database
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void importData(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		int check = checkExists(mhs);
		if(check == 0){
			DON_VI_TCM d = null;
			MonHocM m = null;
			ArrayList<MonHocM> ls = mhs;
			for (MonHocM l : ls) {
				d = new DON_VI_TCM();
				d = dv.getMa(l.getMa_don_vi());
				if(d!=null){
					m = new MonHocM();
					m.setMa(l.getMa());
					m.setTen(l.getTen());
					m.setSo_tc(l.getSo_tc());
					m.setSo_tiet_lt(l.getSo_tiet_lt());
					m.setSo_tiet_th(l.getSo_tiet_th());
					m.setId_don_vi_ql(d.getId_don_vi_tc());
					//System.out.println(m.getMa() + "  " + m.getTen() + "  " + m.getSo_tc() + "  " + m.getSo_tiet_lt() +"  " + m.getSo_tiet_th()+"  "+d.getId_don_vi_tc());
					dao.Insert(m);
				}
			}
			map.put("success", "true");
			map.put("msg", "Import dữ liệu thành công");
		}else{
			map.put("success", "false");
			map.put("msg", "Mã môn học " + mhs.get(check).getMa() + " đã tồn tại trong cở sở dữ liệu");
		}
		String returnFlag = JSONObject.fromObject(map).toString();
		PrintWriter out = response.getWriter();
		out.println(returnFlag);
		out.flush();
		out.close();
	}
}